//
//  NSDate+range.m
//  
//
//  Created by JIRENTIANXIANG on 6/27/15.
//
//

#import "NSDate+range.h"
#import "NSDate+format.h"

@implementation NSDate (range)

-(NSDate*)localDate
{
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:self];
    NSDate *localDate = [self  dateByAddingTimeInterval: interval];
    return localDate;
}

-(NSDateComponents*)dateComponents
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitWeekday;
    NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:self];
    return dateComponents;
}

-(BOOL)isWithinToday
{
    return [[NSCalendar currentCalendar] isDateInToday:self];
}

-(BOOL)isPast
{
    NSDate* now=[NSDate date];
    if ([self compare:now]==NSOrderedAscending) {
        return YES;
    }
    return NO;
}

-(BOOL)isPastWithinOneMinute
{
    if (![self isPast]) {
        return NO;
    }
    NSTimeInterval timeInterval=[self timeIntervalSinceNow];
    return timeInterval+60>0;
}

-(BOOL)isPastWithinOneHour
{
    if (![self isPast]) {
        return  NO;
    }
    NSTimeInterval timeInterval=[self timeIntervalSinceNow];
    return timeInterval+60*60>0;
}

-(BOOL)isPastWithinToday
{
    if (![self isPast]) {
        return NO;
    }
    return [[NSCalendar currentCalendar] isDateInToday:self];
}

-(BOOL)isWithinYesterday
{
    return [[NSCalendar currentCalendar] isDateInYesterday:self];
}

-(BOOL)isWithinTheDayBeforeYesterday
{
    return [[NSCalendar currentCalendar] isDate:self inSameDayAsDate:[NSDate dateWithTimeIntervalSinceNow:-2*24*60*60]];
}

//-(BOOL)isBeforeTheDayBeforeYesterday
//{
//    if (![self isPast]) {
//        return NO;
//    }
//    NSCalendar* calendar=[NSCalendar currentCalendar];
//    if ([calendar isDateInToday:self]) {
//        return NO;
//    }
//    if ([calendar isDateInYesterday:self]) {
//        return NO;
//    }
//    if ([calendar isDate:self inSameDayAsDate:[NSDate dateWithTimeIntervalSinceNow:-2*24*60*60]]) {
//        return NO;
//    }
//    return YES;
//}

-(NSInteger)weekdayIndex
{
    NSDateComponents* components=self.dateComponents;
    return components.weekday;
}

-(NSArray*)weekdays
{
    NSDate* sunday=[self numberOfDaysAgo:[self weekdayIndex]-1];
    NSMutableArray* weekdays=[NSMutableArray array];
    for (int i=0; i<7; i++) {
        [weekdays addObject:[sunday numberOFDaysLater:i]];
    }
    return weekdays;
}

-(NSDate*)numberOfDaysAgo:(NSUInteger)days
{
    return [NSDate dateWithTimeIntervalSinceNow:-86400*days];
}

-(NSDate*)numberOFDaysLater:(NSUInteger)days
{
    return [NSDate dateWithTimeIntervalSinceNow:86400*days];
}

@end
